package main

import (
	"flag"
	"log"
	"sync"
	"time"

	"nggs/random"

	protocol "nggs/network/protocol/protobuf/v3"
	link "nggs/network/tcp/v3"
	"nggs/network/tcp/v3/benchmark/msg"
)

var (
	flagAddr         = flag.String("a", "127.0.0.1:8080", "listen addr, default=127.0.0.1:8080")
	flagMessageCount = flag.Int("m", 1000000, "message count, default = 1000000")
)

func main() {
	flag.Parse()

	client, err := link.Dial(*flagAddr, msg.Protocol, 64)
	checkErr(err)
	log.Printf("Connect to %s", *flagAddr)
	clientSessionLoop(client)

	//util.WaitExitSignal()
}

func clientSessionLoop(session *link.Session) {
	start := time.Now()
	log.Println("Starting to send")

	ch := make(chan protocol.IMessage)
	var count int
	var wg sync.WaitGroup
	wg.Add(1)

	go func() {
		for {
			recv, _, err := session.Receive()
			if err != nil {
				log.Println(err)
				break
			}
			//log.Printf("client recv: %v", recv)
			ch <- recv.(protocol.IMessage)
		}
		session.Close()
	}()

	content := random.String(1024)

	go func() {
	loop:
		for {
			select {
			case iMsg := <-ch:
				switch iMsg.MessageID() {
				case msg.S2C_Pong_MessageID():
					send := msg.New_C2S_Ping()
					//send.Content = util.String(util.Int(0, 64))
					//send.Content = util.String(1024)
					send.Content = content
					err := session.Send(send, 0)
					checkErr(err)
					//log.Printf("client send: %v", send)
					count++
					if count > 0 && count%10000 == 0 {
						log.Println(count)
					}
					if count == *flagMessageCount {
						break loop
					}
				}
			}
		}
		wg.Done()
	}()

	send := msg.New_C2S_Ping()
	send.Content = random.String(random.Int(8, 1024))
	//send.SetContent(util.String(4096))
	err := session.Send(send, 0)
	checkErr(err)

	wg.Wait()

	elapsed := time.Since(start)
	log.Printf("Elapsed %s", elapsed)

	x := int(float32(*flagMessageCount*2) / (float32(elapsed) / float32(time.Second)))
	log.Printf("Msg per sec %v", x)
}

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
